#include "dbplotwidget.h"
#include "ui_dbplotwidget.h"
#include "qcustomplot.h"
#include <QtDebug>

dbPlotWidget::dbPlotWidget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::dbPlotWidget)
{
    ui->setupUi(this);

    m_pCustomPlot = ui->widget_plot;

    initPlotWidget();

    connect(m_pCustomPlot, SIGNAL(selectionChangedByUser()), this, SLOT(selectionChanged()));
}

dbPlotWidget::~dbPlotWidget()
{
    delete ui;
}


void dbPlotWidget::setDbInfo(const QString &dbFileName, const QString &dbCommName)
{
    setDbFileName(dbFileName);
    setDbCommName(dbCommName);
}

void dbPlotWidget::setDbQueryInfo(const QString &dbTableName, const QString &dbColumnsSql, const QString &dbWhereSql, const QString &dbOrderSql)
{
    setDbTableName(dbTableName);
    setDbColumnsSql(dbColumnsSql);
    setDbWhereSql(dbWhereSql);
    setDbOrderSql(dbOrderSql);
}

void dbPlotWidget::setDbFileName(const QString &dbFileName)
{
    m_dbFileName = dbFileName;
}

QString dbPlotWidget::dbCommName() const
{
    return m_dbCommName;
}

void dbPlotWidget::setDbCommName(const QString &dbCommName)
{
    m_dbCommName = dbCommName;
}

void dbPlotWidget::setDbTableName(const QString &dbTableName)
{
    m_dbTableName = dbTableName;
}

void dbPlotWidget::setDbColumnsSql(const QString &dbColumnsSql)
{
    m_dbColumnsSql = dbColumnsSql;
}

void dbPlotWidget::setDbOrderSql(const QString &dbOrderSql)
{
    m_dbOrderSql = dbOrderSql;
}

void dbPlotWidget::setDbWhereSql(const QString &dbWhereSql)
{
    m_dbWhereSql = dbWhereSql;
}

// 初始化配置曲线控件
void dbPlotWidget::initPlotWidget()
{
    m_pCustomPlot->xAxis->setLabel(tr("时间"));
    QSharedPointer<QCPAxisTickerDateTime> dateTicker(new QCPAxisTickerDateTime);
    dateTicker->setDateTimeFormat("yyyy-MM-dd\nhh:mm:ss");
    m_pCustomPlot->xAxis->setTicker(dateTicker);
    m_pCustomPlot->xAxis->setTicks(true);
    m_pCustomPlot->xAxis->setTickLabels(true);
    m_pCustomPlot->xAxis->setTickLabelRotation(0);

    m_pCustomPlot->yAxis->setLabel("value");
    // 设置选中曲线or图例
    m_pCustomPlot->setInteractions(QCP::iRangeDrag|QCP::iRangeZoom| QCP::iSelectAxes |
                                   QCP::iSelectLegend | QCP::iSelectPlottables);
    m_pCustomPlot->legend->setSelectableParts(QCPLegend::spItems);

    m_pCustomPlot->legend->setVisible(true);
    m_pCustomPlot->legend->setFont(QFont("Helvetica",9));
    m_pCustomPlot->setLocale(QLocale(QLocale::Chinese, QLocale::China));
}


void dbPlotWidget::SetPlotVisible(int index, bool visible)
{
    if(index > m_PlotItems.count())
    {
        return;
    }

    m_PlotItems[index].bVisible = visible;
    m_pCustomPlot->graph(index)->setVisible(visible);
    m_pCustomPlot->replot();
}

void dbPlotWidget::setXAxisFiled(QString filed)
{
    m_xAxisFiled = filed;
}

void dbPlotWidget::AddOnePlot(QString name, QString filed, QColor color, QString yLabel, bool bVisible)
{
    PlotItemInfo item;
    item.name = name;
    item.filed = filed;
    item.color = color;
    item.yLabel = yLabel;
    item.bVisible = bVisible;

    QPen pen;
    pen.setStyle(Qt::SolidLine);
    pen.setWidth(2);
    pen.setColor(color);

    m_pCustomPlot->addGraph();
    m_pCustomPlot->graph(m_PlotItems.count())->setPen(pen);
    m_pCustomPlot->graph(m_PlotItems.count())->setName(name);
    m_pCustomPlot->graph(m_PlotItems.count())->setVisible(bVisible);

    m_PlotItems.append(item);

}

// 执行查询操作
bool dbPlotWidget::query()
{
    // 获取数据库
    if(!QSqlDatabase::contains(m_dbCommName))
    {
        m_Database = QSqlDatabase::addDatabase("QSQLITE", m_dbCommName);
        m_Database.setDatabaseName(m_dbFileName);
    }

    m_Database = QSqlDatabase::database(m_dbCommName);

    if(!m_Database.isOpen())
    {
        m_Database.open();
    }

    QString strColumn = m_xAxisFiled + ",";
    for(int i=0; i<m_PlotItems.count(); i++)
    {
        strColumn += m_PlotItems.at(i).filed;
        if(i!=m_PlotItems.count()-1)
        {
            strColumn+=",";
        }
    }

    //执行查询
    m_sqlString = QString("select %1 from %2 %3 order by %4 DESC;")
            .arg(strColumn)
            .arg(m_dbTableName)
            .arg(m_dbWhereSql)
            .arg(m_xAxisFiled);

    QSqlQuery query(m_Database);
    query.exec(m_sqlString);
    QSqlRecord rec = query.record();

    //qDebug() << m_sqlString;

    // 查询并填充数据
    bool hasData = false;
    QVector<double> xData;
    QVector<QVector<double>> yData(m_PlotItems.count());
    while(query.next())
    {
        hasData = true;

        xData.append(query.value(0).toDateTime().toTime_t());

        for(int i=0; i<m_PlotItems.count(); i++)
        {
            yData[i].append(query.value(i+1).toDouble());
        }
    }

    // 显示
    if(hasData)
    {
        for(int i=0; i<m_PlotItems.count(); i++)
        {
            m_pCustomPlot->graph(i)->setData(xData, yData[i]     );
        }

        m_pCustomPlot->xAxis->setRange(xData.first(), xData.last());
        m_pCustomPlot->rescaleAxes(true);
        m_pCustomPlot->replot();
    }

    return hasData;
}

// 选中曲线时的操作
void dbPlotWidget::selectionChanged()
{
    if (m_pCustomPlot->xAxis->selectedParts().testFlag(QCPAxis::spAxis) || m_pCustomPlot->xAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
            m_pCustomPlot->xAxis2->selectedParts().testFlag(QCPAxis::spAxis) || m_pCustomPlot->xAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
    {
        m_pCustomPlot->xAxis2->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
        m_pCustomPlot->xAxis->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
    }
    // make left and right axes be selected synchronously, and handle axis and tick labels as one selectable object:
    if (m_pCustomPlot->yAxis->selectedParts().testFlag(QCPAxis::spAxis) || m_pCustomPlot->yAxis->selectedParts().testFlag(QCPAxis::spTickLabels) ||
            m_pCustomPlot->yAxis2->selectedParts().testFlag(QCPAxis::spAxis) || m_pCustomPlot->yAxis2->selectedParts().testFlag(QCPAxis::spTickLabels))
    {
        m_pCustomPlot->yAxis2->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
        m_pCustomPlot->yAxis->setSelectedParts(QCPAxis::spAxis|QCPAxis::spTickLabels);
    }


    // synchronize selection of graphs with selection of corresponding legend items:
    for (int i=0; i<m_pCustomPlot->graphCount(); ++i)
    {
        QCPGraph *graph = m_pCustomPlot->graph(i);
        QCPPlottableLegendItem *item = m_pCustomPlot->legend->itemWithPlottable(graph);
        if ((item->selected() || graph->selected())&&(graph->visible()))
        {
            item->setSelected(true);
            //注意：这句需要Qcustomplot2.0系列版本
            graph->setSelection(QCPDataSelection(graph->data()->dataRange()));
            graph->rescaleValueAxis(true);

            m_pCustomPlot->yAxis->setLabel(m_PlotItems.at(i).yLabel);
            //这句1.0系列版本即可
            //graph->setSelected(true);
        }
    }
}
